<?php
namespace app\admin\controller;
use app\admin\model\system\SysuserModel;
use app\common\service\system\SysprojectService;
use think\facade\Config;
use think\facade\Db;
use think\facade\Filesystem;

class PublicController extends AdminCommonController
{
    public function index()
    {
        $sessionid = session('sysuser');
        session(null, 'think');
        if (isset ($sessionid)) {
            $this->redirect('Index/index');
        } else {
            return $this->fetch();
        }
    }

    // 用户登出
    public function logout()
    {
        $sessionid = session('sysuser');
        if (isset ($sessionid)) {
            session(null);
            //session_destroy();
            //$this->assign("jumpUrl", __URL__ . '/index/');
            $this->success('登出成功！', 1);
        } else {
            $this->success('已经登出！', 1);
        }
    }

    // 登录检测
    public function checklogin()
    {
        $account = input("account","",'trim');
        $password = md5(input("password","",'trim'));
        $verify = (input("verify"));
        if (empty ($account)) {
            $this->error('帐号必须！');
        }
        if (empty ($password)) {
            $this->error('密码必须！');
        }
        //使用用户名、密码和状态的方式进行认证
        $con['account'] = $account;
        $con['password'] = $password;
        $user = SysuserModel::where($con)->find();
        if (empty($user)) {
            $this->error('用户名或密码错误', 0);
        } elseif ($user['status'] == '禁用') {
            $this->error('您的账户已被禁用！', 0);
        } else {
            $this->loginToSession($user->toArray());
            $this->success('登录成功！', 1);
        }
    }

    /**
     * @param $user
     * @param $nodesname
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loginToSession($user): void
    {
        //取出相关角色信息
        $role = Db::query("select * from sysrole sr,sysrole_user sru WHERE sr.id=sru.role_id and sru.user_id=:user_id", ['user_id' => $user['id']]);
        $user['sysrole'] = $role;
        //取出相关可访问资源信息
        $node = Db::query("select DISTINCT sysmenu.* from sysmenu inner join sysrole_menu on sysmenu.id=sysrole_menu.menu_id inner join sysrole_user on sysrole_menu.role_id=sysrole_user.role_id and sysrole_user.user_id=:user_id", ['user_id' => $user['id']]);
        $user['sysmenu'] = $node;
        //重组权限节点为数组
        if ($user['account'] == 'admin') {
            $node = Db::name("sysmenu")->select()->toArray();
            $user['sysmenu'] = $node;
            foreach ($node as $key => $value) {
                $nodesname[$key] = $value['name'];
                session('menunames', $nodesname);
            }
        } else {
            foreach ($user['sysmenu'] as $key => $value) {
                $nodesname[$key] = $value['name'];
                session('menunames', $nodesname);
            }
        }
        session('sysuser', $user);
    }

    public function echarts()
    {
        return $this->fetch();
    }

    public function info()
    {
        return $this->fetch();
    }

    public function top()
    {
        foreach (session('sysuser.sysrole') as $item) {
            $roles[] = $item['title'];
        }
        $this->assign('sysuser_role', implode('|', $roles));
        $this->assign("menulist", erwei(session('sysuser.sysmenu')));
        $projectlist = SysprojectService::getUserProjectList();
        session('projectid', $projectlist->toArray()[0]['id']);
        session('projectname', $projectlist->toArray()[0]['name']);
        $this->assign("projectlist", json_encode($projectlist, JSON_UNESCAPED_UNICODE));
        return $this->fetch();
    }

    public function configlist()
    {
        // dump(Session::all());
        // $map[] = ['id', '>', 0];
        // $res = SysuserModel::where($map)->limit(100)->with(['roles'])->order('id desc')->select();
        // $resrole = SysroleModel::where($map)->limit(100)->with(['menus'])->order('id desc')->select();
        // // $res=UserModel::with(['patients'])->limit(10)->select();
        // // $res=YypatientModel::limit(10)->select();
        // dump(SysmenuModel::getLastSql());
        // dump($res->toArray());
        // dump($resrole->toArray()); 
        // dump(session());
        dump(Config::get());
    }

    public function userinfo()
    {
        $isPost = $this->request->isPost();
        if ($isPost) {
            $userid = input('id');
            $password = input('password');
            $password = md5($password);
            $sysuser = new SysuserModel();
            $res = SysuserModel::update(['password' => $password], ['id' => $userid]);
            if ($res) {
                $this->success("成功");
            } else {
                $this->error("失败" . $sysuser->getError());
            }
        } else {
            return $this->fetch();
        }
    }

    // 后台首页 查看系统信息
    public function main()
    {
        $info = [
            '操作系统'                 => PHP_OS,
            '运行环境'                 => $_SERVER["SERVER_SOFTWARE"],
            'PHP运行方式'              => php_sapi_name(),
            'PHP版本'                => phpversion(),
            'mysql_version'        => $this->_mysql_version(),
            'mysql_size'           => $this->_mysql_db_size(),
            'ThinkPHP版本'           => app()->version() . ' [ <a href="http://thinkphp.cn" target="_blank">查看最新版本</a> ]',
            '上传附件限制'               => ini_get('upload_max_filesize'),
            '执行时间限制'               => ini_get('max_execution_time') . '秒',
            '服务器时间'                => date("Y年n月j日 H:i:s"),
            '北京时间'                 => gmdate("Y年n月j日 H:i:s", time() + 8 * 3600),
            '服务器域名/IP'             => $_SERVER['SERVER_NAME'] . ' [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]',
            '剩余空间'                 => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
            'register_globals'     => get_cfg_var("register_globals") == "1" ? "ON" : "OFF",
            //'magic_quotes_gpc'     => (1 === get_magic_quotes_gpc()) ? 'YES' : 'NO',
            //'magic_quotes_runtime' => (1 === get_magic_quotes_runtime()) ? 'YES' : 'NO',
            '系统开发'                 => ' 杨庆 393978119@qq.com',
            // '系统设置'                 => ' <a href="/admin/public/configlist" target="_blank">查看系统设置</a> ',
        ];
        $this->assign('info1', $info);
        // dump($info);
        return $this->fetch();
    }

    private function _mysql_version()
    {
        $version = Db::query("select version() as ver");
        return $version[0]['ver'];
    }

    private function _mysql_db_size()
    {
        $sql = "SHOW TABLE STATUS FROM `" . Config::get('database.connections.mysql.database') . '`';
        // dump($sql);
        $tblPrefix = Config::get('database.prefix');
        if ($tblPrefix != null) {
            $sql .= " LIKE '{$tblPrefix}%'";
        }
        $row = Db::query($sql);
        $size = 0;
        foreach ($row as $value) {
            $size += $value["data_length"] + $value["index_length"];
        }
        return round(($size / 1048576), 2) . 'M';
    }

    public function upload()
    {
        // 获取表单上传文件
        $type = input('get.type');
        $files = request()->file();
        try {
            validate([
                'file' => [
                    'fileSize' => 1024 * 1024 * 5,
                    'fileExt'  => 'jpg,jpeg,png,bmp,gif',
                    'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上，很重要我认为！
                ]
            ])->check($files);
            $savename = [];
            foreach ($files as $file) {
                if ($type == 'staff') {
                    $savename[] = Filesystem::disk('public')->putFile('upload/staffpic', $file);
                }
                if ($type == 'staffdeal') {
                    $savename[] = Filesystem::disk('public')->putFile('upload/staffpic', $file);
                }
            }
            $this->success('上传成功', 1, ($savename));
        } catch (\think\exception\ValidateException $e) {
            echo $e->getMessage();
        }
    }



    public function map()
    {
        return $this->fetch();
    }


    public function welcome0()
    {
        return $this->fetch();
    }

    public function welcome1()
    {
        return $this->fetch();
    }

    public function welcome2()
    {
        return $this->fetch();
    }

    public function welcome3()
    {
        return $this->fetch();
    }
}
